package com.lbj.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class JDKProxy {
    public static void main(String[] args) {
        //创建接口实现类代理对象
        Class[] interfaces = {UserDao.class};

        /*Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() {
            @Override   //匿名内部类方法
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return null;
            }
        })*/

        //接口实现类的代理对象
        UserDaoImpl userDao = new UserDaoImpl();
        UserDaoProxy userDaoProxy = new UserDaoProxy(userDao);  //把UserDao传入UserDaoProxy类中

        UserDao dao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, userDaoProxy);
        int result = dao.add(1, 2);
        System.out.println(result);
    }
}

//创建代理对象代码
class UserDaoProxy implements InvocationHandler{

    //1.创建的是谁的代理对象，把谁传递进来
    private Object obj; // Object=userDaoImpl  obj=dao
    //有参数构造传递
    public UserDaoProxy(Object obj) {
        this.obj = obj;
    }
    //增强逻辑
    @Override           // 对象代理 dao     .方法      方法传递的参数
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //方法之前
        System.out.println("方法执行之前....."+method.getName()+":传递的参数..."+ Arrays.toString(args));
        //被增强的方法执行
        Object res = method.invoke(obj, args);  // dao.add();
        //方法之后
        System.out.println("方法执行之后......."+obj);  //obj=com.lbj.jdk.UserDaoImpl@26b418
        return res;
    }
}
